import subprocess
import sys
import logging
from feature_add.generate_feature import generate_main
JS_FILE = "cluster_server.js"
# 我们将监听工作进程的输出，这是服务器准备就绪的明确信号
SERVER_READY_SIGNAL = "监听 http://localhost:3000"


def start_and_manage_js_server():
    """
    启动 JS 服务器，等待其就绪，运行任务，然后关闭服务器。
    """
    process = None
    try:
        logging.info(f"正在启动 JS 服务器: node {JS_FILE}")
        process = subprocess.Popen(
            ["node", JS_FILE],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            encoding='utf-8'
        )

        logging.info("等待 JS 启动...")
        server_is_ready = False
        # 持续读取进程的输出，直到找到准备就绪的信号
        for line in iter(process.stdout.readline, ''):
            logging.info(f"JS 输出: {line.strip()}")
            if SERVER_READY_SIGNAL in line:
                server_is_ready = True
                logging.info("\n>>> 检测到 JS 服务器已准备就绪！\n")
                break

        # 如果循环结束但服务器未就绪，可能是启动失败
        if not server_is_ready:
            logging.info("错误：未能检测到服务器启动信号，JS 进程可能已崩溃。")
            # 检查进程是否已经退出
            if process.poll() is not None:
                logging.info(f"JS 进程已退出，返回码: {process.returncode}")
            return

        # --- js已就绪，现在运行 Python 任务 ---
        generate_main()
    except FileNotFoundError:
        logging.info(f"错误: 未找到 'node' 命令。请确保已安装 Node.js 并将其添加到系统 PATH 中。")
        sys.exit(1)
    except Exception as e:
        logging.info(f"发生未知错误: {e}")
    finally:
        # --- 确保服务器被关闭 ---
        if process and process.poll() is None:  # 检查进程是否仍在运行
            logging.info("\n>>> Python 任务完成，正在关闭 JS 服务器...")
            process.terminate()
            try:
                process.wait(timeout=10)
                logging.info(">>> JS 服务器已关闭。")
            except subprocess.TimeoutExpired:
                process.kill()
                logging.info(">>> JS 服务器已被强制终止。")
        else:
            logging.info("JS 服务器进程未运行或已自行退出。")
if __name__ == '__main__':
    start_and_manage_js_server()
